layui.define(['element', 'layer', 'util', 'dropdown', 'theme', 'popup'], function (exports) {

    var element = layui.element;
    var layer = layui.layer;
    var util = layui.util;
    var $ = layui.$;
    var dropdown = layui.dropdown;
    var theme = layui.theme;
    var popup = layui.popup;

    var admin = {
        render: function (options) {
            options.menuUrl = options.menuUrl || null //左侧菜单接口
            options.baseMineUrl = options.baseMineUrl || null //我的基本资料
            options.pwdMineUrl = options.pwdMineUrl || null //我的修改密码
            options.logOutMineUrl = options.logOutMineUrl || null //我的退出登录
            options.clearUrl = options.clearUrl || null //清理缓存

            layui.data("admin", { key: "options", value: options })

            // 获取左侧菜单
            admin.getLeftMenu()
            // 样式点击事件
            theme.click()
            // 左侧菜单点击事件
            element.on('nav(admin-left-nav)', function () {
                admin.sideMin("on")
            });
            // 菜单添加标签
            $("body").delegate("[kllxs-href]", "click", function () {
                var href = $(this).attr("kllxs-href");
                var text = $(this).html();
                admin.tabAddFun({
                    text: text,
                    href: href
                })
            })
            // 标签切换事件
            element.on('tab(admin-tab)', function (data) {
                var href = $(this).attr("lay-id");
                var dom = $(`[kllxs-href="${href}"]`);
                if (dom.length) {
                    var name = dom.parent().prop("tagName")
                    if (name === "DD") {
                        dom.parents("li").addClass("layui-nav-itemed")
                    }
                    $(".layui-layout-admin .layui-side .layui-this").removeClass("layui-this")
                    dom.parent().addClass("layui-this")
                } else {
                    $(".layui-layout-admin .layui-side .layui-this").removeClass("layui-this")
                }
                $(`iframe[src="${href}"]`).on('load', function () {
                    layer.closeAll("loading")
                })
            });
            //批量Click事件
            util.event('kllxs-on', {
                // 全屏事件
                fullState: function () {
                    var i = $(this).find("i")
                    if (i.hasClass("layui-icon-screen-full")) {
                        admin.fullScreen()
                        i.removeClass("layui-icon-screen-full").addClass("layui-icon-screen-restore")
                    } else {
                        admin.exitFullScreen()
                        i.removeClass("layui-icon-screen-restore").addClass("layui-icon-screen-full")

                    }
                },
                // 左侧菜单事件
                menuLeft: function (othis) {
                    // console.log(othis)
                    var i = $(othis).find("i")
                    var status = i.hasClass("layui-icon-spread-left")
                    admin.sideMin(status ? "on" : "off")
                },
                // 右侧隐藏菜单
                menuRight: function () {
                    var themeDom = theme.render()
                    layer.open({
                        type: 1,
                        id: "more-menu",
                        title: '更多',
                        content:
                            `<div class="more-menu-list layui-show-xs-block">
                            <a class="more-menu-item" href="javascript:;" kllxs-href="${options.baseMineUrl}">
                                <i class="layui-icon layui-icon-username"></i> 基本资料
                            </a>
                            <a class="more-menu-item" href="javascript:;" kllxs-href="${options.pwdMineUrl}">
                                <i class="layui-icon layui-icon-vercode"></i> 修改密码
                            </a>
                            <a class="more-menu-item" href="javascript:;" kllxs-on="logOut">
                                <i class="layui-icon layui-icon-close-fill"></i> 退出登录
                            </a>
                        </div>
                        <div class="layui-card-header">配色方案</div>${themeDom}`,
                        area: ['260px', '100%'],
                        offset: 'rt', // 右上角
                        anim: 'slideLeft', // 从右侧抽屉滑出
                        shadeClose: true,
                        scrollbar: false
                    });
                },
                // 手机端遮罩层
                mobileShade: function () {
                    admin.sideMin("off")
                },
                // 刷新当前标签
                refreshTab: function () {
                    var loadIndex = layer.load();
                    var dom = $(".admin-body .layui-tab .layui-tab-content .layui-show").children("iframe")
                    var src = dom.attr("src")
                    dom.attr("src", src)
                    dom.on('load', function () {
                        layer.close(loadIndex)
                    })
                },
                // 左滑动
                rollLeft: function () {
                    admin.tabScroll("left")
                },
                // 右滑动
                rollRight: function () {
                    admin.tabScroll("right")
                },
                // 标签更多操作
                rollMore: function () {
                    dropdown.render({
                        elem: this, // 触发事件的 DOM 对象
                        show: true, // 外部事件触发即显示
                        data: [
                            { title: '关 闭 当 前', id: 'current' },
                            { title: '关 闭 其 他', id: 'other' },
                            { title: '关 闭 全 部', id: 'all' }
                        ],
                        click: function (obj) {
                            if (obj.id === "current") {
                                var tabActivity = $(".admin-body .layui-tab-title .layui-this")
                                if (tabActivity.attr("id") != "admin-tab-id") {
                                    element.tabDelete('admin-tab', tabActivity.attr("lay-id"))
                                }
                            } else {
                                $.each($('.admin-body .layui-tab-title li'), function (k, v) {
                                    var id = $(v).attr("id")
                                    var layid = $(v).attr("lay-id")
                                    var isThis = $(v).hasClass("layui-this")
                                    if (id !== "admin-tab-id") {
                                        if (obj.id === "other" && isThis) {
                                            return true;
                                        } else {
                                            element.tabDelete('admin-tab', layid)
                                        }
                                    }
                                })
                            }
                        },
                        align: 'center', // 右对齐弹出
                    })
                },
                // 我的操作
                onMine: function () {
                    dropdown.render({
                        elem: this, // 触发事件的 DOM 对象
                        show: true, // 外部事件触发即显示
                        data: [
                            { title: '基本资料', id: 'MineInfo' },
                            { title: '修改密码', id: 'PassWord' },
                            { title: '退出登录', id: 'LogOut' }
                        ],
                        click: function (obj) {
                            switch (obj.id) {
                                case 'MineInfo':
                                    admin.tabAddFun({
                                        text: `<i class="layui-icon layui-icon-username" style="font-size: 19px;"></i>
                                                <span class="layui-left-nav">${obj.title}</span>`,
                                        href: options.baseMineUrl
                                    })
                                    break;
                                case 'PassWord':
                                    admin.tabAddFun({
                                        text: `<i class="layui-icon layui-icon-vercode" style="font-size: 19px;"></i>
                                        <span class="layui-left-nav">${obj.title}</span>`,
                                        href: options.pwdMineUrl
                                    })
                                    break;
                                default:
                                    admin.logOutFun(options.logOutMineUrl)
                            }
                        },
                        align: 'center', // 右对齐弹出
                    })
                },
                //退出登录
                logOut: function () {
                    admin.logOutFun(options.logOutMineUrl)
                },
                //清理缓存
                clearCache: function () {
                    $.get(options.clearUrl, function (res) {
                        popup.msg(res)
                    })
                }
            });
        },
        // 获取左侧菜单
        getLeftMenu: function () {
            var options = layui.data("admin", { key: "options" })
            $.get(options.menuUrl, function (res) {
                if (res.code == 1) {
                    admin.getLeftMenuFun(res.data)
                } else {
                    layer.msg(res.msg)
                }
            })
        },
        // 左侧菜单函数
        getLeftMenuFun: function (data) {
            var html = "";
            
            layui.each(data, function (k, v) {
                if ((v.href && v.href != "") || v.children) {
                    var href = ''
                    var children = ''
                    if (v.href) {
                        href = `kllxs-href="${v.href}"`
                    }
                    html += `<li class="layui-nav-item" >
                                <a href="javascript:;" ${href}>
                                    <i class="${v.icon}"></i>
                                    <cite>${v.title}</cite>
                                </a>`;
                    if (v.children) {
                        layui.each(v.children, function (kk, vv) {
                            children += `<dd>
                                <a href="javascript:;" kllxs-href="${vv.href}">
                                    <i class="${vv.icon}"></i>
                                    <span class="layui-left-nav">${vv.title}</span>
                                </a>
                            </dd>`
                        })
                        children = `<dl class="layui-nav-child">${children}</dl>`
                    }
                    html += `${children}</li >`;
                    $(".layui-layout-admin .layui-side .layui-side-scroll")
                        .html(`<ul class="layui-nav layui-nav-tree" lay-filter="admin-left-nav">${html}</ul>`)

                    element.render('nav', 'admin-left-nav');
                }
            })
        },
        // 退出登录函数
        logOutFun: function (url) {
            layer.confirm('确定退出登录吗', { icon: 3 }, function () {
                $.get(url, function (res) {
                    popup.msg(res)
                }).fail(function () {
                    layer.msg("退出登录接口有误!");
                })
            });
        },
        // 标签添加函数
        tabAddFun: function (obj) {
            var demo = $(`.admin-body .layui-tab-title [lay-id="${obj.href}"]`)
            if (demo.length === 1) {
                element.tabChange('admin-tab', obj.href);
            } else {
                var load = layer.load()
                element.tabAdd('admin-tab', {
                    title: obj.text,
                    content: `<iframe src="${obj.href}" frameborder="0"></iframe>`,
                    id: obj.href, // 实际使用一般是规定好的id，这里以毫秒数模拟
                    change: true // 是否添加完毕后即自动切换
                })
            }
        },
        // 伸缩菜单函数
        sideMin: function (switchStart) {
            var iconSpread = $(`[kllxs-on="menuLeft"]`).find("i")
            if (switchStart === "on") {
                //切换到展开状态的 icon，箭头：←
                iconSpread.removeClass("layui-icon-spread-left").addClass("layui-icon-spread-right");
                $(".layui-layout-admin").removeClass("kllxs-side-mini")
            } else {
                //切换到搜索状态的 icon，箭头：→
                iconSpread.removeClass("layui-icon-spread-right").addClass("layui-icon-spread-left");
                $(".layui-layout-admin").addClass("kllxs-side-mini")
            }
        },
        // 标签滑动函数
        tabScroll: function (direction) {
            var tabTitle = $(".admin-body .layui-tab-title")
            var left = tabTitle.scrollLeft();
            if (direction === "left") {
                tabTitle.animate({
                    scrollLeft: left - 450
                }, 200);
            } else {
                tabTitle.animate({
                    scrollLeft: left + 450
                }, 200);
            }
        },
        // 进入全屏
        fullScreen: function () {
            var el = document.documentElement;
            var rfs = el.requestFullScreen || el.webkitRequestFullScreen;
            if (typeof rfs != "undefined" && rfs) {
                rfs.call(el);
            } else if (typeof window.ActiveXObject != "undefined") {
                var wscript = new ActiveXObject("WScript.Shell");
                if (wscript != null) {
                    wscript.SendKeys("{F11}");
                }
            } else if (el.msRequestFullscreen) {
                el.msRequestFullscreen();
            } else if (el.oRequestFullscreen) {
                el.oRequestFullscreen();
            } else if (el.webkitRequestFullscreen) {
                el.webkitRequestFullscreen();
            } else if (el.mozRequestFullScreen) {
                el.mozRequestFullScreen();
            } else {
                miniAdmin.error('浏览器不支持全屏调用！');
            }
        },
        //退出全屏
        exitFullScreen: function () {
            var el = document;
            var cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.exitFullScreen;
            if (typeof cfs != "undefined" && cfs) {
                cfs.call(el);
            } else if (typeof window.ActiveXObject != "undefined") {
                var wscript = new ActiveXObject("WScript.Shell");
                if (wscript != null) {
                    wscript.SendKeys("{F11}");
                }
            } else if (el.msExitFullscreen) {
                el.msExitFullscreen();
            } else if (el.oRequestFullscreen) {
                el.oCancelFullScreen();
            } else if (el.mozCancelFullScreen) {
                el.mozCancelFullScreen();
            } else if (el.webkitCancelFullScreen) {
                el.webkitCancelFullScreen();
            } else {
                miniAdmin.error('浏览器不支持全屏调用！');
            }
        }
    }

    $(function () {
        // 执行页面已经加载完成后需要的操作
        $(".loader-main").hide()
    });

    $(document).ready(function () {
        // 获取初始窗口宽度
        var windowWidth = $(window).width();
        // console.log("初始窗口宽度:" + windowWidth);
        if (windowWidth < 768) {
            admin.sideMin("off")
        } else {
            admin.sideMin("on")
        }

        // 监听窗口宽度变化
        $(window).resize(function () {
            var newWindowWidth = $(window).width();
            if (newWindowWidth < 768) {
                admin.sideMin("off")
            } else {
                admin.sideMin("on")
            }
        });
    });

    exports('admin', admin); // 输出模块
});  